class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int>m;
        for (int i = 0; i < nums.size(); i++) {
            m[nums[i]]++;
        }
        struct cmp {
            bool operator()(pair<int, int>& p1, pair<int, int>& p2) {
                return p1.second > p2.second;
            }
        };
        priority_queue<pair<int, int>, vector<pair<int, int> >, cmp>q;
        for (auto &a : m) {
            q.push(a);
            if (q.size() > k) {
                q.pop();
            }
        }

        vector<int>answer;
        while (!q.empty()) {
            answer.push_back(q.top().first);
            q.pop();
        }
        return answer;
    }
};